import {getParams, IParams} from './params'
import {SaeInterface} from './sae'
import {DeployApplicationResponse} from '@alicloud/sae20190506'
import * as step from '@flow-step/step-toolkit'
import {sleep} from '@alicloud/tea-typescript'
import {check} from './check'
import {describeConfig, generateDeployRequest} from './deployUtils'

export async function deploy(params:IParams, sae: SaeInterface) {

    const appConfig= await describeConfig(params, sae)
    const appName = appConfig.appName as string
    const packageType = appConfig.packageType as string
    const deployRequest = generateDeployRequest(params, packageType)

    let deployResponse:DeployApplicationResponse
    try {
        deployResponse = await sae.deployApplication(deployRequest)
    }catch (error:any){
        const message:string = error.message
        if (message.includes('is in progress')){
            step.interaction.appendErrorMessage(params.domestic?'SAE服务异常或当前还有未结束的发布任务，请到SAE控制台检查':'SAE service is experiencing issues or there are ongoing deployment tasks. Please check the SAE console.')
        }else if (message.includes('The parameter is invalid {ImageUrl}')){
            step.interaction.appendErrorMessage(params.domestic?'SAE不能访问您的镜像地址，请到SAE控制台检查':'SAE cannot access your imageUrl. Please check the SAE console.')
        }else{
            step.interaction.appendErrorMessage(message)
        }
        throw new Error(`failed to deployApplication: ${error}`)
    }
    if (deployResponse.body?.code != '200' ) {
        throw new Error(`failed to deploy application: ${deployResponse.body?.message}`)
    }
    const changeOrderId = deployResponse.body?.data?.changeOrderId as string
    step.exportEnvVar('CHANGE_ORDER_ID', changeOrderId)

    step.info(`Current deployment details URL: https://sae.console.aliyun.com/#/AppList/ChangeOrderDetail?appId=${params.APPLICATION_ID}&regionId=${params.regionID}&appName=${appName}&changeOrderId=${changeOrderId}`)
    // sleep 5s
    await sleep(5000)
    step.info(`CHECKING DEPLOYMENT STATUS`)
    const params_new = getParams()
    await check(params_new,sae)

    step.addOutput(`APP_NAME=${appName}`)
    step.addOutput(`CHANGE_ORDER_ID=${changeOrderId}`)
    step.interaction.runAction('CHECK')
    step.addOutput(`GLOBAL_CANCEL_HOOK_ACTION=TERMINATE`)
}